﻿using System;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;

namespace 异步编程
{
    /// <summary>
    /// 异步编程不等于是多线程，单线程也能异步。
    /// 异步是不能阻塞，多线程是可以阻塞的。
    /// 异步需要线程池。
    /// 异步适合长耗时的任务。
    /// 异步的开销，比较小。线程的开销要大一些。
    /// </summary>
    internal class Program
    {
        static void Main(string[] args)
        {
            //TaskDemo1();


            Main();






            Console.WriteLine("Hello World!");
        }


        static async Task Main()
        {
            Helper.PrintThread("Before");
            await FooAsync();
            Helper.PrintThread("After");
        }

        static async Task FooAsync()
        {
            Helper.PrintThread("Before");
            await Task.Delay(1000);
            Helper.PrintThread("After");
        }





        /// <summary>
        /// 任务的各种状态
        /// </summary>
        static void TaskDemo1()
        {
            Task<string> task = new Task<string>(() =>
            {
                Thread.Sleep(1500);
                return "done";
            });


            Console.WriteLine(task.Status); // Created
            task.Start();
            Console.WriteLine(task.Status); // WaitingToRun
            Thread.Sleep(1000);
            Console.WriteLine(task.Status); // Running
            Thread.Sleep(1000);
            Console.WriteLine(task.Status); // RanToCompletion
        }
    }

    class Helper
    {
        private static int index = 1;
        public static void PrintThread(string? message = null, [CallerMemberName] string? name = null)
        {
            var title = $"{index}:{name}";
            if(!string.IsNullOrEmpty(message))
            {
                title += $" @ {message}";
                Console.WriteLine($"{title}");
                Console.WriteLine($"线程id:{Environment.CurrentManagedThreadId}");
                Interlocked.Increment(ref index);
            }
        }
    }

}
